package com.service.firstapp.controller;

import com.huawei.paas.cse.tcc.annotation.TccTransaction;
import com.service.firstapp.bean.People;
import com.service.firstapp.bean.PeopleInfo;
import com.service.firstapp.provider.PeopleInfoService;
import com.service.firstapp.provider.PeopleService;
import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.servicecomb.provider.pojo.RpcReference;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * Created by wjh on 2018/3/27.
 */
@RestSchema(schemaId = "people")
@RequestMapping(path = "/firstapp/people", produces = MediaType.APPLICATION_JSON)
public class PeopleController {

    private static final Logger logger = LoggerFactory.getLogger(PeopleController.class);

    @RpcReference(microserviceName = "providerApp_1", schemaId = "peopleService")
    private PeopleService remotePeopleService;

    @RpcReference(microserviceName = "providerApp_2", schemaId = "peopleInfoService")
    private PeopleInfoService remotePeopleInfoService;

    @Value("${secondapp.host}")
    public String secondAppHost;

    @Value("${thirdapp.host}")
    public String thirdAppHost;

    //用于configmap调试
    @Value("${test.name}")
    public String helloName;

    @RequestMapping(value = "/hello_rpc", method = RequestMethod.GET)
    public Object helloRpcTest(@RequestParam(value = "name") String name) {
        logger.info("================ consumerApp hello_rpc:" + name + " =================");
        return remotePeopleService.doRpcTest(name);
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Object helloTest(@RequestParam(value = "name") String name) {
        logger.info("================ consumerApp hello:" + name + " =================");
        String resp = "hello " + helloName;
        if (name.equals("exception")) {
            throw new RuntimeException("exception");
        }
        return resp;
    }

    @RequestMapping(value = "/hello/rest", method = RequestMethod.GET)
    public Object helloTestRest(@RequestParam(value = "name") String name) {
        logger.info("================ consumerApp hello rest:" + name + " =================");
        RestTemplate restTemplate = RestTemplateBuilder.create();
        String prefix = "cse://providerApp_1";
        String resp = restTemplate.postForObject(prefix + "/secondapp/people/hello/" + name, null, String.class, name);
        if (name.equals("exception")) {
            throw new RuntimeException("exception");
        }
        return resp;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object getPeopleList() {
        //三种方式，restTemplate httpClient,Rpc
        //RestTemplate restTemplate = RestTemplateBuilder.create();
        //JSONArray json = HttpRequestUtil.httpGet(secondAppHost+"/secondapp/people/list");
        long currentTime = System.currentTimeMillis();
        List json = remotePeopleService.getPeopleList();
        logger.info("耗时：" + (System.currentTimeMillis() - currentTime));
        return json;
    }

    @RequestMapping(value = "/{people_id}", method = RequestMethod.GET)
    public Object getPeopleById(@PathVariable(value = "people_id") Integer peopleId) {
        //JSONArray array = HttpRequestUtil.httpGet(secondAppHost + "/secondapp/people/" + peopleId);
        long currentTime = System.currentTimeMillis();
        People people = remotePeopleService.getPeopleById(peopleId);
        PeopleInfo peopleInfo = remotePeopleInfoService.getPeopleInfoById(people.getPeopleId());
        logger.info("耗时：" + (System.currentTimeMillis() - currentTime));
        return peopleInfo;
    }

    @TccTransaction(confirmMethod = "confirm", cancelMethod = "cancel")
    @RequestMapping(method = RequestMethod.POST)
    public Object addPeople(@RequestBody People people){
        long currentTime = System.currentTimeMillis();
        people.setStatus(0);
        //JSONObject peopleJson = JSONObject.fromObject(people);
        PeopleInfo peopleInfo = new PeopleInfo();
        peopleInfo.setPeopleId(people.getPeopleId());
        peopleInfo.setSex(0);
        peopleInfo.setHeight(177);
        peopleInfo.setStatus(0);
        //JSONObject peopleInfoJson = JSONObject.fromObject(peopleInfo);
        //JSONObject resp1 = HttpRequestUtil.httpPost(secondAppHost + "/secondapp/people", peopleJson);
        //JSONObject resp2 = HttpRequestUtil.httpPost(thirdAppHost + "/thirdapp/people_info", peopleInfoJson);
        People resp = remotePeopleService.addPeople(people);
        logger.info("1耗时：" + (System.currentTimeMillis() - currentTime));
        long currentTime2 = System.currentTimeMillis();
        if(null != resp){
            remotePeopleInfoService.addPeopleInfo(peopleInfo);
            logger.info("2耗时：" + (System.currentTimeMillis() - currentTime2));
        }
        logger.info("总耗时：" + (System.currentTimeMillis() - currentTime));
        return people;
    }

    @TccTransaction(confirmMethod = "confirmRest", cancelMethod = "cancelRest")
    @RequestMapping(value = "/rest",method = RequestMethod.POST)
    public Object addPeopleRest(@RequestBody People people) {
        long currentTime = System.currentTimeMillis();
        people.setStatus(0);
        RestTemplate restTemplate = RestTemplateBuilder.create();
        String prefix1 = "cse://providerApp_1";
        String prefix2 = "cse://providerApp_2";

        PeopleInfo peopleInfo = new PeopleInfo();
        peopleInfo.setPeopleId(people.getPeopleId());
        peopleInfo.setSex(0);
        peopleInfo.setHeight(177);
        peopleInfo.setStatus(0);
        Map resp = restTemplate.postForObject(prefix1 + "/secondapp/people", people, Map.class);
        if (null != resp) {
            restTemplate.postForObject(prefix2 + "/thirdapp/people_info", peopleInfo, Map.class);
        }
        logger.info("1、2总耗时：" + (System.currentTimeMillis() - currentTime));
        return people;
    }

    public void confirm(People people) {
        logger.info("==========consumerApp confirm==========");
    }

    public void cancel(People people) {
        logger.info("==========consumerApp cancel==========");
    }

    public void confirmRest(People people) {
        logger.info("==========consumerApp confirm==========");
    }

    public void cancelRest(People people) {
        logger.info("==========consumerApp cancel==========");
    }

}
